<template>
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>参数列表</el-breadcrumb-item>
  </el-breadcrumb>


  <el-card class="box-card">
    <el-alert
      title="注意，只允许为第三方设置相关参数!"
      type="warning"
      show-icon :closable="false">
    </el-alert>

<!--    选择商品分类    -->

      <span class="demonstration">选择商品分类:</span>
      <el-cascader
        :options="goodsClassify"
        @change="handleChange" size="small" :props="props" clearable >
      </el-cascader>
<!--      tab切换栏-->
    <el-tabs v-model="activeName" >
      <el-tab-pane label="动态参数" name="first">
          <!--              动态参数模块-->
        <el-button type="primary" :disabled="flag_btn" @click="adddtcs">添加动态参数</el-button>
        <el-table :data="dt_data" stripe border >
          <el-table-column type="expand" width="60px">
            <template slot-scope="scope"  >
              <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index"   @close="handleClose(index,scope.row)">{{item}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"  @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button class="button-new-tag" size="small" @click="showInput(scope.row)">+ 新增</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="editsubmit(scope.row.cat_id,scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteclassify(scope.row.cat_id,scope.row.attr_id)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>
      </el-tab-pane>


      <el-tab-pane label="静态属性" name="second">
        <!--              静态参数模块-->
        <el-button type="primary" :disabled="flag_btn" @click="addjtcs">添加静态参数</el-button>
        <el-table :data="jt_data" stripe border >
          <el-table-column type="expand" width="60px">
            <template slot-scope="scope"  >
              <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope.row)">{{item}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"  @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button class="button-new-tag" size="small" @click="showInput(scope.row)">+ 新增</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="editsubmit(scope.row.cat_id,scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteclassify(scope.row.cat_id,scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>

<!--  动态添加参数的文子框-->
  <el-dialog
    title="动态添加参数"
    :visible.sync="dtdialogVisible"
    width="50%"  @close="dtgb">

    <el-form :model="dtruleForm" :rules="dtrules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="动态参数" prop="attr_name">
        <el-input v-model="dtruleForm.attr_name"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="dtdialogVisible = false" >取 消</el-button>
    <el-button type="primary" @click="submitaddattr">确 定</el-button>
  </span>
  </el-dialog>
  <!--  静态添加参数的文子框-->
  <el-dialog
    title="静态添加参数"
    :visible.sync="jtdialogVisible"
    width="50%" @close="jtgb">

    <el-form :model="jtruleForm" :rules="jtrules" ref="jtruleForm" label-width="100px" class="demo-ruleForm" >
      <el-form-item label="静态参数" prop="attr_name">
        <el-input v-model="jtruleForm.attr_name"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="jtdialogVisible = false" >取 消</el-button>
    <el-button type="primary" @click="submitaddattrjt">确 定</el-button>
  </span>
  </el-dialog>

<!--  编辑的文子框-->
  <el-dialog
    title="编辑"
    :visible.sync="editdialogVisible"
    width="50%">

    <el-form :model="edit_data " :rules="editrules" ref="editruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="活动名称" prop="attr_name">
        <el-input v-model="edit_data.attr_name"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editattr">确 定</el-button>
  </span>
  </el-dialog>

</div>
</template>

<script>
export default {
  data() {
    return {
      classify: [],
      goodsClassify: [],
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'first',
      dt_id: '',
      dt_data: [],
      jt_data: [],
      // 编辑的原数据
      edit_data: [],
      // 编辑的属性类型
      edit_attr_sel: '',
      flag_btn: true,
      dtdialogVisible: false,
      jtdialogVisible: false,
      editdialogVisible: false,
      dtruleForm: {
        attr_name: '',
    },
      jtruleForm: {
        attr_name: '',
      },
      dtrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]},
      jtrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]},
      editrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]}
  }},
  created() {
    // 调用获取商品分类函数
    this.getgoodslist()
  },
  methods: {
    async getgoodslist() {
      const {data: res} = await this.$http.get(`categories`)
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.goodsClassify = res.data
    },
    async handleChange(value) {
      if (value.length === 0) { //当没有选中
        this.dt_data = []
        this.jt_data = []
        return this.flag_btn = true
      }
      this.flag_btn = false
      // 每次使用前，清空
      this.jt_data = []
      this.dt_data = []
      // 拿到最后的id
      this.dt_id = value[value.length - 1]
      // 调用获取动态参数的函数
      this.getdtcs()
      // 调用获取静态参数的函数
      this.getjtcs()
    },
    async getdtcs() {
      // 发起axios请求
      const {data: res} = await this.$http.get(`categories/${this.dt_id}/attributes`,{params: {sel: 'many'}})
      if (res.meta.status !== 200) return this.$message.error('获取动态参数失败')
      if (res.data.length === 0) {
        return this.activeName = 'second'
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      this.dt_data = res.data
    },
    async getjtcs() {
      // 发起axios请求
      const {data: res} = await this.$http.get(`categories/${this.dt_id}/attributes`,{params: {sel: 'only'}})
      if (res.meta.status !== 200) return this.$message.error('获取静态参数失败')
      if (res.data.length === 0) {
        return this.activeName = 'first'
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      this.jt_data = res.data
    },
    adddtcs() {
      this.dtdialogVisible = !this.dtdialogVisible
    },
    addjtcs() {
      this.jtdialogVisible = !this.jtdialogVisible
    },
    submitaddattr() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.dtdialogVisible = !this.dtdialogVisible
          const {data: res} = await  this.$http.post(`categories/${this.dt_id}/attributes`,{
            attr_name: this.dtruleForm.attr_name,
            attr_sel: 'many'
          })
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          this.getdtcs()
          this.$message.success('添加成功')
        } else {
          this.$message.error('验证不通过')
          return false;
        }
      });
    },
    submitaddattrjt() {
      this.$refs.jtruleForm.validate(async valid => {
        if (valid) {
          this.jtdialogVisible = !this.jtdialogVisible
          const {data: res} = await  this.$http.post(`categories/${this.dt_id}/attributes`,{
            attr_name: this.jtruleForm.attr_name,
            attr_sel: 'only'
          })
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          this.getjtcs()
          this.$message.success('添加成功')
        } else {
          this.$message.error('验证不通过')
          return false;
        }
      });
    },
    jtgb() {
      this.$refs.jtruleForm.resetFields()
    },
    dtgb() {
      console.log('1')
      this.$refs.ruleForm.resetFields()
    },
    async deleteclassify(id,attrid) {
      const results = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      if (results !== 'confirm') return false
      const {data: res} = await this.$http.delete(`categories/${id}/attributes/${attrid}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getjtcs()
      this.getdtcs()
    },
    editsubmit(id,attrid) {
      this.editdialogVisible = !this.editdialogVisible
      if (this.activeName === 'first') {  // 如果是动态参数
        // 调用根据id查询参数的函数
        this.getdatabyid(id,attrid,'many')
      }
      else {  // 如果是静态参数
        // 调用根据id查询参数的函数
        this.getdatabyid(id,attrid,'only')

      }
    },
    async getdatabyid(id,attrid,arrtsel) {
      this.edit_attr_sel = arrtsel
      const {data: res} = await this.$http.get(`categories/${id}/attributes/${attrid}`,{
        params: {attr_sel: arrtsel}
      })
      if (res.meta.status !== 200) return this.message.error('获取参数失败')
      // 定义一个数组接收数据
      this.edit_data = res.data
    },
    editattr() {
      this.$refs.editruleForm.validate(async valid => {
        if (valid) {
          const {data: res} = await this.$http.put(`categories/${this.edit_data.cat_id}/attributes/${this.edit_data.attr_id}`,{
            attr_name: this.edit_data.attr_name,
            attr_sel: this.edit_attr_sel
          })
          if (res.meta.status !== 200) return this.$message.error('编辑失败')
          this.$message.success('编辑成功')
          this.getjtcs()
          this.getdtcs()
          this.editdialogVisible = !this.editdialogVisible
        } else {
          this.$message.error('验证错误')
          return false;
        }
      });
    },
    async handleClose(index,row) {
      row.attr_vals.splice(index,1)
      const {data: res} = await this.$http.put(`categories/${this.dt_id}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false;
      const {data: res} = await this.$http.put(`categories/${this.dt_id}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('编辑提交参数失败')
      this.$message.success('编辑提交参数成功')


    }
  }
}
</script>

<style scoped>
.el-breadcrumb {
  margin: 0 0 15px 15px;
}
.el-pagination {
  margin-top: 10px;
}
.el-cascader {
  margin-left: 15px;
}
.el-alert {
  margin-bottom: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin-right: 5px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
